/**
 * 
 */
package cc.rico.redis.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

/**
 * @author rico 2016年8月20日
 *
 */
public class ShardedJedisPoolUtil {
	private static final Logger logger = LoggerFactory.getLogger(ShardedJedisPoolUtil.class);
	// redis host
	private static final String host = "192.168.223.143";
		
	private static ShardedJedisPool pool;
	static {
		logger.info("## ShardedJedisPoolUtil.init...");
		ResourceBundle bundle = ResourceBundle.getBundle("config"); 

		// 连接池参数设置
		GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
	    poolConfig.setMaxTotal(Integer.valueOf(bundle.getString("redis.connection.maxTotal")));
	    poolConfig.setMaxIdle(Integer.valueOf(bundle.getString("redis.connection.maxIdle")));
	    poolConfig.setMinIdle(Integer.valueOf(bundle.getString("redis.connection.minIdle")));
	    
		poolConfig.setTestOnBorrow(Boolean.valueOf(bundle.getString("redis.connection.testOnBorrow")));
		poolConfig.setTestOnCreate(Boolean.valueOf(bundle.getString("redis.connection.testOnCreate")));
		poolConfig.setTestOnReturn(Boolean.valueOf(bundle.getString("redis.connection.testOnReturn")));
		poolConfig.setTestWhileIdle(Boolean.valueOf(bundle.getString("redis.connection.testWhileIdle")));
		
		// redis 客户端分片
	    List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();  
	    shards.add(new JedisShardInfo(host, 6379));  
	    shards.add(new JedisShardInfo(host, 6380));
		
		pool = new ShardedJedisPool(poolConfig, shards);
	}
	
	private ShardedJedisPoolUtil() {
		
	}
	
	public static ShardedJedisPool getInstance() {
		return pool;
	}
	
	public static ShardedJedis getShardedJedis() {
		return pool.getResource();
	}
	
	public static void close(ShardedJedis shardedJedis) {
		shardedJedis.close();
	}
	
}
